package com.doyens.gmall.product.controller;

import com.doyens.gmall.common.result.Result;
import io.swagger.annotations.Api;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("admin/product")
@Api("文件上传接口")
public class FileUploadController {
    @Value("${fileServer.url}")
    private String fileUrl;
    @RequestMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception{

            /*
            1.加载配置文件
            2.初始化当前文件
            3.创建TrackerClient
            4.创建TrackerServer
            5.创建StorageClient1
            6.文件上传
         */

        String config=this.getClass().getResource("/tracker.conf").getFile();
        String path=null;
        if (config != null){
            //初始化
            ClientGlobal.init(config);
            //创建TrackerClient
            TrackerClient trackerClient = new TrackerClient();
           //创建TrackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            //创建StorageClient1
            StorageClient1 storageClient1 = new StorageClient1();
            //            6.文件上传
            //获取文件后缀名
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            path = storageClient1.upload_appender_file1(file.getBytes(), extension, null);
            System.out.println("文件上传完之后返回的路径：" + path);
            System.out.println("完整的路径: " + fileUrl + path);
        }
        return Result.ok(fileUrl + path);
    }
}
